import { IMessage } from 'qq-guild-bot';
import nunjucks from 'nunjucks';
import { dirname, join } from 'path';
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { getPu, readYaml } from '../../src/lib/tool';
import { sendImage } from '../../src/lib/tool';
import moment from 'moment';
// 时区设置为中国
import 'moment/locale/zh-cn';
import { stringify } from 'yaml';
moment.locale('zh-cn');

export const rule = {
  签到: {
    reg: '^/签到$', //匹配消息正则，命令正则
    priority: 1000, //优先级，越小优先度越高
    describe: '签到' //【命令】功能说明
  }
};

export async function 签到(e: { eventType: string; msg: IMessage }) {
  // 私聊禁用
  if (e.eventType === 'DIRECT_MESSAGE_CREATE') {
    return;
  }
  let qd = join(__dirname, './resources/yaml/qiandao.yaml');

  let qdjson = readYaml(qd);
  let now = moment().format('YYYY-MM-DD HH:mm:ss');
  if ((qdjson ?? '') !== '' && (qdjson[e.msg.author.id] ?? '') !== '') {
    // 签到那天结束的时间
    var start = moment(qdjson[e.msg.author.id], 'YYYY-MM-DD HH:mm:ss').endOf('day');
    //  当前时间
    var end = moment(now, 'YYYY-MM-DD HH:mm:ss');

    if (moment.duration(end.diff(start)).asDays() < 0) {
      let message = {
        content: `<@!${e.msg.author.id}> 您已签到请明天再来`,
        msg_id: e.msg.id // 可选，消息id，如果指定则会回复该消息
      };
      let { data } = await client.messageApi.postMessage(e.msg.channel_id, message);
      return true;
    }
  }

  // 使用模板
  let res = nunjucks.render(join(__dirname, './html/index.html'), {
    img: e.msg.author.avatar,
    name: e.msg.author.username,
    time: now
  });

  //   递归创建文件夹
  mkdirSync(join(__dirname, `./resources/html`), { recursive: true });
  mkdirSync(join(__dirname, `./resources/img`), { recursive: true });
  // 创建模板html
  writeFileSync(join(__dirname, `./resources/html/${e.msg.author.id}.html`), res);
  //   截图
  let img = await getPu(
    join(__dirname, `./resources/html/${e.msg.author.id}.html`),
    '.bj',
    join(__dirname, `./resources/img/${e.msg.author.id}.jpg`)
  );
  //   发送本地图片
  if (img) {
    await sendImage(e.msg.channel_id, {
      file_image: join(__dirname, `./resources/img/${e.msg.author.id}.jpg`),
      msg_id: e.msg.id
    });

    if (!existsSync(qd)) {
      mkdirSync(dirname(qd), { recursive: true });
    }
    if ((qdjson ?? '') === '' || typeof qdjson === 'string') {
      qdjson = {};
    }
    qdjson[e.msg.author.id] = now;
    writeFileSync(qd, stringify(qdjson));
  }
  return true;
}
